from pathlib import Path
import json

from PIL import Image
import wx


def init_db(img_folder: Path, save_folder: Path):
    save_names = tuple([pa.name for pa in save_folder.glob('*.json')])

    index = 0
    flag = True
    db_jsons = []
    for img_path in img_folder.glob('*.jpg'):
        db_json, db_exists = read_db(save_folder, img_path.name)
        if db_exists:
            if flag:
                index += 1
        else:
            flag = False
            db_json = {
                'path': img_path,
                'txt': 'null'}
        db_jsons.append(db_json)
    return db_jsons, index


def read_db(save_folder: Path, name: str):
    db_path = save_folder / (name + '.json')
    if db_path.exists():
        with open(db_path) as f:
            db_json = json.load(f)
    if db_json.has_key('txt') and db_json['txt'] != 'null':
        db_exists = True
    else:
        db_exists = False
        db_json = {}
    return db_json, db_exists


def save_db(save_folder: Path, name: str, db_json):
    db_path = save_folder / (name + '.json')
    with open(db_path, 'w') as f:
        json.dump(db_json, f)
    return 'Saved'


def resize(img: Image, max_size=1300):
    if img.width > img.height:
        rate = max_size / img.width
    else:
        rate = max_size / img.height
    
    width, height = int(img.width * rate), int(img.height * rate)
    img = img.resize((width, height), Image.ANTIALIAS)
    return img


def pilimage_to_wxbitimage(img: Image):
    wximage = wx.EmptyImage(img.width, img.height)
    wximage.SetData(img.convert( 'RGB' ).tostring() )
    return wximage.ConvertToBitmap()
